import { PermissionState } from '@/types/store/permission';
import { RouteRecordRaw } from 'vue-router';
import { defineStore } from 'pinia';
import { asyncRoutesOfLocal, constantRoutes } from '@/router';
//import { listRoutes } from '@/api/system/menu';

const modules = import.meta.glob('../../views/**/**.vue');
export const Layout = () => import('@/layout/index.vue');

const hasPermission = (roles: string[], route: RouteRecordRaw) => {
	
	if (route.meta && route.meta.roles) {
		if ((route.meta.roles as string[]).includes('any') || roles.includes("root")) {
			return true;
		}
		return roles.some((role) => {
			if (route.meta?.roles !== undefined) {
				return (route.meta.roles as string[]).includes(role);
			}
		});
	}
	return false;
};

export const filterAsyncRoutes = (
	routes: RouteRecordRaw[],
	roles: string[]
) => {
	const res: RouteRecordRaw[] = [];
	routes.forEach((route) => {
		const tmp = { ...route } as any;
		if (hasPermission(roles, tmp)) {			
            if(tmp.component && typeof(tmp.component)=="string"){
				if (tmp.component == 'Layout') {
					tmp.component = Layout;
				} else {
					const component = modules[`../../views/${tmp.component}.vue`] as any;
					if (component) {
						tmp.component = modules[`../../views/${tmp.component}.vue`];
					} else {
						tmp.component = modules[`../../views/error-page/404.vue`];
					}
				}
			}
			if (tmp.children) {
				tmp.children = filterAsyncRoutes(tmp.children, roles);
			}
			res.push(tmp);
		}
	});
	return res;
};

const usePermissionStore = defineStore({
	id: 'permission',
	state: (): PermissionState => ({
		routes: [],
		addRoutes: [],
	}),
	actions: {
		setRoutes(routes: RouteRecordRaw[]) {
			this.addRoutes = routes;
			this.routes = constantRoutes.concat(routes);
		},
		generateRoutes(roles: string[]) {
			return new Promise((resolve, reject) => {
				//从服务器下载路由列表 后续可以这样干
				/*
				listRoutes()
				  .then((response) => {
					const asyncRoutes = response.data;
					const accessedRoutes = filterAsyncRoutes(asyncRoutes, roles);
					this.setRoutes(accessedRoutes);
					resolve(accessedRoutes);
				  })
				  .catch((error) => {
					reject(error);
				  });
				*/			 
				//本地动态路由
				let accessedRoutes
				//if (roles.includes('admin')) {
				// accessedRoutes = asyncRoutes || []
				// } else {
				accessedRoutes = filterAsyncRoutes(asyncRoutesOfLocal, roles)
				// }
				this.setRoutes(accessedRoutes);
				resolve(accessedRoutes);
			});
		},
	},
});

export default usePermissionStore;
